add.vue<template>
  <div class="app-container">
    <el-form ref="user" :model="user" :rules="rules" label-width="120px">
      <el-form-item label="用户名"  prop="name">
        <el-input v-model="user.name"  />
      </el-form-item>


      <el-form-item label="用户手机号"  prop="mobile">
        <el-input v-model="user.mobile"  :style="{width: '25%'}"  placeholder="请输入手机号" clearable/>
      </el-form-item>

      <el-form-item label="用户密码"  prop="password">
        <el-input v-model="user.password"  :style="{width: '25%'}"  placeholder="请输入密码" clearable/>
      </el-form-item>

      <el-form-item label="VIP类型" prop="vip">
        <el-select v-model="user.vip" clearable placeholder="请选择">
          <el-option :value="0" label="非VIP"/>
          <el-option :value="1" label="VIP"/>
        </el-select>
      </el-form-item>

      <el-form-item label="用户头像">
        <el-upload
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          class="avatar-uploader"
          action="http://localhost:8080/upload/">
          <img v-if="user.avatar" :src="user.avatar" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"/>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button :disabled="saveBtnDisabled" type="primary" @click="addOrUpdate">保存</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>

    </el-form>
  </div>
</template>

<script>

import user from "../../api/user";


export default {
  data() {
    const validateName = (rule, value, callback) => {
        if(this.user.id) {
          if (this.oldName != value) {

            // 后台方法
            user.nameIsExist(value).then(res => {
              if (res.data === true) {
                callback()
              } else {
                callback(new Error('该名称已经被使用'))
              }
            });
          }
        }else{
          user.nameIsExist(value).then(res => {
            if (res.data === true) {
              callback()
            } else {
              callback(new Error('该名称已经被使用'))
            }
        });
    }
    }
    return {
      user: {
        id:'',
        avatar: '',
        name:'',
        mobile: undefined,
        vip: 0

      },
      saveBtnDisabled: false,
      oldName: null,
      rules: {
        name: [
          { required: true, message: '请输入用户名字' },
          {  trigger: 'change' }
        ],
        mobile: [
          {
          required: true,
          message: '请输入手机号'},
          {trigger: 'change'}
        ],
        password: [
          {
            required: true,
            message: '请输入密码'},
          {trigger: 'change'}
        ],
        vip: [
          { required: true, message: '请选择用户VIP类型', trigger: 'change' }
        ]
      }
    }
  },
  methods: {

    resetForm() {
      this.$refs['user'].resetFields();
    },
    handleAvatarSuccess(res, file) {
      this.user.avatar = res.data
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 20
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 20MB!')
      }
      return isJPG && isLt2M
    },
    addOrUpdate() {
      this.$refs['user'].validate((valid) => {
        if (valid) {
          if (this.user.id != null ) {
            this.updateUser();
          } else {
            console.log(this.user.id)
            this.addUser()
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    addUser() {
      user.addUser(this.user).then(res => {
        this.$message.success(res.message)
        this.$router.push({ path: '/user/list' })
      })
    },
    updateUser() {
      user.updateUser(this.user).then(res => {
        this.$message.success(res.message)
        this.$router.push({ path: '/user/list' })
      })
    },

    findById(id) {
      user.findById(id).then(res => {
        this.user = res.data
        this.oldName = this.user.name;
      })
    }
  },
    created(){
      if (this.$route.params && this.$route.params.id) {
        const id = this.$route.params.id
        this.findById(id)
      }else{
        this.user = {avatar: ""};
      }

    },
    // 监听
    watch: {
      // 监听路由的变化
      $route(to, from){
        // 路由变化，将数据模型清空
        this.user = {avatar: ""};
      }
    }
}
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
